package org.leetcode.middle.leetcode39;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class Solution2 {
    public List<List<Integer>> combinationSum(int[] candidates, int target) {

        Arrays.sort(candidates);

        backtracking(candidates, target, 0);

        return res;
    }

    int sum = 0;
    List<List<Integer>> res = new ArrayList<>();
    List<Integer> item = new ArrayList<>();

    private void backtracking(int[] candidates, int target, int index) {
        if (sum == target) {
            res.add(new ArrayList<>(item));
        }

        if (sum>target) {
            return;
        }

        for (int i = index; i < candidates.length; i++) {
            item.add(candidates[i]);
            sum += candidates[i];
            backtracking(candidates, target, i);
            item.remove(item.size() - 1);
            sum -= candidates[i];
        }
    }
}
